package com.lzh.hosp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.hosp.model.Dict;
import com.lzh.hosp.service.DictService;
import com.lzh.hosp.mapper.DictMapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 59399
* @description 针对表【dict(组织架构表)】的数据库操作Service实现
* @createDate 2023-03-15 12:14:44
*/
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
    implements DictService{

    @Override
    public List<Dict> listChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getValue();
            boolean isChildren = this.isChildren(dictId);
            dict.setHasChildren(isChildren);
            dict.setText(dict.getName());
            if (isChildren){
                //继续查询出儿子节点
                List<Dict> childData = this.listChildren(dictId);
                dict.setChildren(childData);
            }
        }
        return dictList;
    }

    @Override
    public String getDictName(Long value) {
        QueryWrapper<Dict>wrapper = new QueryWrapper<>();
        wrapper.eq("value",value);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict.getName();
    }

    @Override
    public String getParentName(Long value) {
        QueryWrapper<Dict>wrapper = new QueryWrapper<>();
        wrapper.eq("value",value);
        Dict dict = baseMapper.selectOne(wrapper);
        return this.getDictName(dict.getParentId());
    }

    @Override
    public Long getParentValue(Long value) {
        QueryWrapper<Dict>wrapper = new QueryWrapper<>();
        wrapper.eq("value",value);
        Dict dict = baseMapper.selectOne(wrapper);
        Long parentId = dict.getParentId();

        QueryWrapper<Dict>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("value",parentId);
        Dict parentDict = baseMapper.selectOne(queryWrapper);
        return parentDict.getValue();
    }

    //判断id下面是否有子节点
    private boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}




